import sys
import json
import smtplib
from email.mime.text import MIMEText
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("email")

@mcp.tool()
def send_email(to, subject, body):
    msg = MIMEText(body, 'plain', 'utf-8')
    msg['From'] = '1357724823@qq.com'
    msg['To'] = to
    msg['Subject'] = subject

    try:
    # 修改服务器地址为普通QQ邮箱的SMTP服务器
        smtp = smtplib.SMTP_SSL('smtp.qq.com', 587)
    # 使用正确的授权码（需在QQ邮箱设置中获取）
        smtp.login('1357724823@qq.com', 'zkhrrbrvwoaeidbj')
        smtp.sendmail('1357724823@qq.com', to, msg.as_string())
        smtp.quit()
        return {"status": "success", "message": "邮件发送成功"}
    except smtplib.SMTPAuthenticationError as e:
        return {"status": "error", "message": f"认证失败: {str(e)}，请检查邮箱账号和授权码"}
    except smtplib.SMTPException as e:
         return {"status": "error", "message": f"SMTP协议错误: {str(e)}"}
    except Exception as e:
        return {"status": "error", "message": f"发送邮件时出错: {str(e)}"}

def main():
# 测试数据
    test_data = {
     "arguments": {
            "to": "darkchess@2925.com",
            "subject": "MCP邮件助手测试",
            "body": "MCP邮件助手测试，hihi  by dark"
        }
     }
try:
        result = send_email(
            test_data['arguments']['to'], 
            test_data['arguments']['subject'], 
            test_data['arguments']['body']
        )
except Exception as e:
    result = {"status": "error", "message": f"调用发送函数时出错: {str(e)}"}

    print(json.dumps(result))
    sys.stdout.flush()

# 启动MCP服务器
if __name__ == "__main__":
    print("准备启动MCP服务器")
    mcp.run()